library(rgdal)
library(maptools)
if (!require(gpclib)) install.packages("gpclib", type="source")
gpclibPermit()
library(plyr)
library(tidyverse)
library(ggpmisc)
library(readit)
library(reshape)

library(urbnmapr)

states_sf <- get_urbn_map("states", sf = TRUE)
treatment_dates <- readRDS("Data/treatment_dates.rds")
pres_vote_dat <- readit("Data/1868_2020_presvote.dta")

dat.plot <- data.frame(state = unique(pres_vote_dat$state[pres_vote_dat$state != "US"]))
dat.plot$treatment[dat.plot$state %in% treatment_dates$state] <- "Lottery"
dat.plot$treatment[!dat.plot$state %in% treatment_dates$state] <- "No_Lottery"

states_sf$treatment <- "No_Lottery"

states_sf$treatment[states_sf$state_abbv %in% dat.plot$state[dat.plot$treatment == "Lottery"]] <- "Lottery"


dat.table <- data.frame(state = treatment_dates$state, state_long = state.name[match(treatment_dates$state,state.abb)], dates = as.Date(treatment_dates$treatment.date))

dat.table <- dat.table[,-1]
dat.table.2 <- data.frame(lotteries = dat.table[,-2])

dat.table$dates <- format(dat.table$dates, "%D")

dat.table


colnames(dat.table) <- c("COVID-19 Lotteries", "Date Implemented")

dat.table.2 <- dat.table[order(dat.table$`Date Implemented`),]

#for pdf
states_sf %>% ggplot(aes(fill=treatment),color="white") + geom_sf(color = "black") + scale_fill_manual("COVID-19 Lottery", values = c("darkslategray4","white")) + labs(x = NULL, y = NULL, title = NULL) +
  annotate(geom = "table", x = 0, y = 1000, label = list(dat.table.2),size = 3, hjust = -1.2, vjust = .75) +
  theme_void() + theme(legend.position = "none", plot.margin = margin(0, 6, 0, 0, "cm"))

#for tiff
states_sf %>% ggplot(aes(fill=treatment),color="white") + geom_sf(color = "black") + scale_fill_manual("COVID-19 Lottery", values = c("darkslategray4","white")) + labs(x = NULL, y = NULL, title = NULL) +
  annotate(geom = "table", x = 0, y = 1000, label = list(dat.table.2),size = 3, hjust = -1.3, vjust = .75) +
  theme_void() + theme(legend.position = "none", plot.margin = margin(0, 6, 0, 0, "cm"))
